package com.ys.service.overseas.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.dto.AddDto;
import com.ys.entity.flow.YspModel;
import com.ys.entity.overseas.TosProductSelection;
import com.ys.entity.overseas.TosProductSelectionItem;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsCol;
import com.ys.entity.sys.YsMenu;
import com.ys.enume.flow.FlowEnum;
import com.ys.mapper.overseas.OverseasMapper;
import com.ys.mapper.overseas.TosProductSelectionItemMapper;
import com.ys.mapper.overseas.TosProductSelectionMapper;
import com.ys.service.flow.YspTaskService;
import com.ys.service.overseas.TosProductSelectionService;
import com.ys.util.CheckUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @Author: fxz
 * @CreateTime: 2024-12-17
 * @Description: HW商品选品库
 * @Version: 1.5
 */
@Service("tosProductSelectionService")
public class TosProductSelectionServiceImpl implements TosProductSelectionService {

    @Autowired
    private CheckUtil checkUtil;

    @Autowired
    private TosProductSelectionMapper tosProductSelectionMapper;

    @Autowired
    private TosProductSelectionItemMapper tosProductSelectionItemMapper;

    @Autowired
    private YspTaskService yspTaskService;

    @Autowired
    private OverseasMapper overseasMapper;

    /**
     * 新增HW商品选品库
     * @param params
     * @param subData
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R add(Map<String, Object> params, String subData) throws Exception {
        //验证
        String msg = yzMsg(params);
        if (msg != null){
            return R.error(msg);
        }
        TosProductSelection tosProductSelection = JSON.parseObject(JSON.toJSONString(params), TosProductSelection.class);
        if (new TosProductSelection().setBid(tosProductSelection.getBid()).count() != 0){
            return R.error("该单号已存在，核实后再操作!");
        }
        // 验证是否有详情数据
        JSONArray detailJA = JSON.parseArray(subData);
        if (detailJA == null || detailJA.size() == 0) {
            return R.error("详情数据不能为空");
        }
        Integer count = 0;
        for (int i = 0; i < detailJA.size(); i++) {
            JSONObject detailJO = detailJA.getJSONObject(i);
            TosProductSelectionItem tosProductSelectionItem = JSON.parseObject(JSON.toJSONString(detailJO), TosProductSelectionItem.class);
            count = new TosProductSelection().setVgsBm(tosProductSelection.getVgsBm())
                    .addLeftJoin("TOS_ProductSelectionItem B ON B.pid = A.id")
                    .where("A.vgsBm = '"+ tosProductSelection.getVgsBm() + "'  AND B.code = '"+tosProductSelectionItem.getCode()+"'")
                    .count();
            if (count > 0){
                return R.error(tosProductSelection.getVgsBm()+"运营公司下,已存在商品编码:"+tosProductSelectionItem.getCode());
            }
        }

        String loginUserId = ShiroUtils.getUserId();
        TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();

        tosProductSelection.setStatus(1);
        tosProductSelection.setCreateChangeId(tsUserChange.getId());
        tosProductSelection.setEffectStock(FlowEnum.EffectStock.NOT_EFFECT.value);
        tosProductSelectionMapper.insert(tosProductSelection);

        for (int i = 0; i < detailJA.size(); i++) {
            JSONObject detailJO = detailJA.getJSONObject(i);
            TosProductSelectionItem tosProductSelectionItem = JSON.parseObject(JSON.toJSONString(detailJO), TosProductSelectionItem.class);
            tosProductSelectionItem.setPid(tosProductSelection.getId());
            tosProductSelectionItemMapper.insert(tosProductSelectionItem);
        }

        YsMenu ysMenu = new YsMenu().setId(MenuId.TOS_ProductSelection).queryFirst();
        if (ysMenu.getFlowModelId().longValue() != 0L) {
            YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
            String codeModel = yspModel.getCode();
            String createUserId = ShiroUtils.getUserId();
            yspTaskService.init(codeModel, tosProductSelection.getBid(), createUserId);
        }

        return R.ok(AddDto.gotoEdit("/web/overseas/tosProductSelection/toEdit?bid=" + tosProductSelection.getBid()));
    }

    /**
     * 修改HW商品选品库
     * @param params
     * @param subData
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R edit(Map<String, Object> params, String subData) throws Exception {
        //验证
        String msg = yzMsg(params);
        if (msg != null){
            return R.error(msg);
        }
        TosProductSelection tosProductSelection = JSON.parseObject(JSON.toJSONString(params), TosProductSelection.class);
        if (new TosProductSelection().setBid(tosProductSelection.getBid()).where("A.id != " + tosProductSelection.getId()).count() != 0){
            return R.error("该单号已存在，核实后再操作!");
        }
        // 验证是否有详情数据
        JSONArray detailJA = JSON.parseArray(subData);
        if (detailJA == null || detailJA.size() == 0) {
            return R.error("详情数据不能为空");
        }
        Integer count = 0;
        for (int i = 0; i < detailJA.size(); i++) {
            JSONObject detailJO = detailJA.getJSONObject(i);
            TosProductSelectionItem tosProductSelectionItem = JSON.parseObject(JSON.toJSONString(detailJO), TosProductSelectionItem.class);
            count = new TosProductSelection().setVgsBm(tosProductSelection.getVgsBm())
                    .addLeftJoin("TOS_ProductSelectionItem B ON B.pid = A.id")
                    .where("A.vgsBm = '"+ tosProductSelection.getVgsBm() + "'  AND B.code = '"+tosProductSelectionItem.getCode()+"'" + "AND A.id !=" + tosProductSelection.getId())
                    .count();
            if (count > 0){
                return R.error(tosProductSelection.getVgsBm()+"运营公司下,已存在商品编码:"+tosProductSelectionItem.getCode());
            }
        }
        //判断是否实在制单中
        Integer flowState = yspTaskService.flowState(tosProductSelection.getBid());

        if (flowState != 0){
            return R.error("HW商品选品库单不是制单中,不允许保存!");
        }
        tosProductSelectionMapper.update(tosProductSelection);

        overseasMapper.deleteTosProductSelectionItemPid(tosProductSelection.getId());

        for (int i = 0; i < detailJA.size(); i++) {
            JSONObject detailJO = detailJA.getJSONObject(i);
            TosProductSelectionItem tosProductSelectionItem = JSON.parseObject(JSON.toJSONString(detailJO), TosProductSelectionItem.class);
            tosProductSelectionItem.setPid(tosProductSelection.getId());
            tosProductSelectionItemMapper.insert(tosProductSelectionItem);
        }

        return R.ok(AddDto.gotoEdit("/web/overseas/tosProductSelection/toEdit?bid=" + tosProductSelection.getBid()));
    }

    /**
     * 流转
     * @param id
     * @param loginUserId
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R flowPass(Long id, String loginUserId) throws Exception {
        TosProductSelection tosProductSelection = new TosProductSelection().setId(id).queryFirst();
        if (tosProductSelection == null){
            throw new RuntimeException("HW商品选品库单据不存在,请核实后再操作!");
        }
        String bid = tosProductSelection.getBid();
        try {
            Flow f = yspTaskService.flowPass(bid, loginUserId);
            if (f.getCode() == Flow.Code.FAILED.value) {
                return R.error(f.getMsg());
            } else {
                if (f.getState() == Flow.State.FINISH.value) {
                    tosProductSelection.setEffectStock(1);
                    tosProductSelectionMapper.update(tosProductSelection);
                }
                return R.ok();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 退回
     * @param id
     * @param reason
     * @param loginUserId
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R flowRefuse(Long id, String reason, String loginUserId) throws Exception {
        TosProductSelection tosProductSelection = new TosProductSelection().setId(id).queryFirst();
        if (tosProductSelection == null){
            throw new RuntimeException("HW商品选品库单据不存在,请核实后再操作!");
        }
        String bid = tosProductSelection.getBid();
        try {
            R r = yspTaskService.flowRefuse(bid, reason, loginUserId);
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("HW商品选品库退回失败!");
        }
    }

    /**
     * 驳回
     * @param id
     * @param reason
     * @param loginUserId
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R flowInit(Long id, String reason, String loginUserId) throws Exception {
        TosProductSelection tosProductSelection = new TosProductSelection().setId(id).queryFirst();
        if (tosProductSelection == null){
            throw new RuntimeException("HW商品选品库单据不存在,请核实后再操作!");
        }
        String bid = tosProductSelection.getBid();
        try {
            R r = yspTaskService.flowInit(bid, reason, loginUserId);
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("HW商品选品库驳回失败!");
        }
    }

    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R del(Long id) throws Exception {
        TosProductSelection tosProductSelection = new TosProductSelection().setId(id).queryFirst();
        if (tosProductSelection == null){
            throw new RuntimeException("HW商品选品库单据不存在,请核实后再操作!");
        }

        //判断是否实在制单中
        Integer flowState = yspTaskService.flowState(tosProductSelection.getBid());

        if (flowState != 0){
            throw new RuntimeException("HW商品选品库单不是制单中,不允许删除!");
        }
        yspTaskService.flowDelete(tosProductSelection.getBid(), String.valueOf(tosProductSelection.getCreateChangeId()));

        tosProductSelectionMapper.deleteTrue(id);

        overseasMapper.deleteTosProductSelectionItemPid(tosProductSelection.getId());
        return R.ok("删除成功!");
    }

    private String yzMsg(Map<String, Object> infoMap){
        //验证导入字段
        String backMsg = "";
        //获取pc字段数据
        List<YsCol> listField = new YsCol()
                .where("A.MenuId = "+ MenuId.TOS_ProductSelection)
                .setOrderby("A.SortNo ASC")
                .queryList();
        //验证必填字段的非空；其他字段的长度限制、类型
        try {
            backMsg = checkUtil.checkTableColLengthAndDataType(
                    "TOS_ProductSelection",
                    listField,
                    infoMap,
                    ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1
            );
            if(backMsg!=null && !"".equals(backMsg)){//若有误，则跳过这条信息
                return backMsg;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
